package com.atguigu.flink0922.chapter06;

import com.atguigu.flink0922.bean.UserBehavior;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/3 15:08
 */
public class Flink01_Project_PV_2 {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        
        // 1. 读入数据
        // 2. 对数据进行map封装
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                final String[] data = line.split(",");
                return new UserBehavior(
                    Long.valueOf(data[0]),
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2]),
                    data[3],
                    Long.valueOf(data[4]));
            })
            .keyBy(UserBehavior::getBehavior)
            .process(new KeyedProcessFunction<String, UserBehavior, Long>() {
                long sum;
                @Override
                public void processElement(UserBehavior value, Context ctx, Collector<Long> out) throws Exception {
                    // 进来一条数据, 判断是否为pv, 如果是就+1, 否则就没有操作
                    if ("pv".equalsIgnoreCase(value.getBehavior())) {
                        sum++;
                        out.collect(sum);
                    }
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
